package com.glw.sso.platform.web.aop;

import com.alibaba.fastjson.JSON;
import com.glw.sso.platform.common.exception.ParamValidException;
import com.glw.sso.platform.common.interfaces.Verifiable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName ControllerLogAspect
 * @Version v1.0
 */
@Aspect
@Component
@Slf4j
public class ControllerLogAspect {

    @Around("execution(public * com.glw.*.*.*.controller..*.*(..)) || execution(public * com.glw.*.*.*.base..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == attributes) {
            return null;
        }
        Object obj = null;
        long startTime = System.currentTimeMillis();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        HttpServletRequest request = attributes.getRequest();
        try {
            for (Object ars : joinPoint.getArgs()) {
                //代码方式验参
                if (ars instanceof Verifiable) {
                    ((Verifiable) ars).verifyInput();
                }
            }
            obj = joinPoint.proceed();
        } finally {
            long useTime = System.currentTimeMillis() - startTime;
            log.info("URL:{}, HTTP_METHOD: {}, IP: {} , 方法:{}, 执行时间：{} ,请求参数: {}, response：{}",
                    request.getRequestURL(), request.getMethod(), request.getRemoteAddr(), classMethod, useTime,
                    JSON.toJSONString(joinPoint.getArgs()), JSON.toJSONString(obj));
        }
        return obj;
    }
}
